import prompt from '@ohos.prompt';
import ajax from '../../http/http';
import webSocket from '@ohos.net.webSocket';
import router from '@ohos.router';

export default {
    data: {
        experimentBoxId: -1,
        Temperature: 0,
        Luminance: 0,
        Humidity: 0,
        PM25: 0,
        airQuality: '--',
        LightStatus: 'ON',
        MotorStatus: 'ON',
        deviceList: [],
        curtainDeviceId: null,
        lightDeviceId: 'equipmentCode_lw_004',
        isSleep: false,
        isLove: false,
        time: 3
    },
    onInit() {
        let room = router.getParams().data;
        this.experimentBoxId = room.id;
        this.Temperature = room.temperature;
        this.Luminance = room.luminance;
        this.Humidity = room.humidity;
        this.PM25 = room.pm25;
        if (this.PM25 <= 35) {
            this.airQuality = '优';
        } else if (this.PM25 > 35 && this.PM25 <= 75) {
            this.airQuality = '良';
        } else {
            this.airQuality = '差';
        }

        this.$watch('PM25', () => {
            if (this.PM25 <= 35) {
                this.airQuality = '优';
            } else if (this.PM25 > 35 && this.PM25 <= 75) {
                this.airQuality = '良';
            } else {
                this.airQuality = '差';
            }
        });
        let requestParam = {
            "condition": {
                "experimentBoxId": this.experimentBoxId
            },
            "currentPageNum": 1,
            "pageSize": 99
        };
        ajax.post('/experiment/device/detail/page', requestParam, (result) => {
            this.total = result.data.total;
            console.info("total=" + this.total);
            this.deviceList = result.data.list;
            //获取设备列表之后开始监听实时上报的数据
            this.wsConnectAndListening();
        });
    },

    wsConnectAndListening() {
        let defaultIpAddress = 'ws://117.78.16.25:5551/im/server/' + this.$app.$def.globalData.token+'?client_type=harmonyos';
        let ws = webSocket.createWebSocket();
        ws.connect(defaultIpAddress, (err, value) => {
            if (!err) {
                console.log("connect success");
            } else {
                console.log("connect fail, err:" + JSON.stringify(err));
            }
        });
        ws.on('open', (err, value) => {
            console.log("on open, status:" + value['status'] + ", message:" + value['message']);
        });
        ws.on('message', (err, value) => {
            console.log("Receive Message:" + value);
            //判断返回结果是否是JSON格式
            if (!this.isJsonString(value)) {
                return false;
            }
            let wsData = JSON.parse(value);
            //如果ws接收到的数据为属性上报类型，即"device.property"，则去刷新设备数据
            if (wsData.resource == "device.property") {
                //遍历上报数据的deviceId，当这些deviceId属于当前设备分组deviceList里面，则监听数据
                const res = this.deviceList.findIndex((ev) => {
                    return ev.deviceId === wsData.notify_data.header.device_id;
                });
                if (res >= 0) {
                    let services = wsData.notify_data.body.services;
                    services.forEach(item => {
                        for (let key in item.properties) {
                            switch (key) {
                                case "Temperature":
                                    this.Temperature = item.properties[key];
                                    break;
                                case "Humidity":
                                    this.Humidity = item.properties[key];
                                    break;
                                case "LightStatus":
                                    this.LightStatus = item.properties[key];
                                    this.lightDeviceId = wsData.notify_data.header.device_id;
                                    break;
                                case "MotorStatus":
                                    this.MotorStatus = item.properties[key];
                                    this.curtainDeviceId = wsData.notify_data.header.device_id;
                                    break;
                                case "Luminance":
                                    this.Luminance = item.properties[key];
                                    break;
                                case "PM25":
                                    this.PM25 = item.properties[key];
                                    break;
                            }
                        }
                    })
                }
            }
            //如果ws接收到的数据为属性上报类型，即"device.status"，则去刷新设备在线状态
            if (wsData.resource == "device.status") {
            }

        });
        ws.on('close', (err, value) => {
            console.log("on close, code is " + value.code + ", reason is " + value.reason);
        });
        ws.on('error', (err) => {
            console.log("on error, error:" + JSON.stringify(err));
        });
    },

    isJsonString(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                console.log('error：' + str + '!!!' + e);
                return false;
            }
        }
        console.log('It is not a string!');
        return false;
    },

    //窗帘开关控制，mode=0，表示根据当前的窗帘状态进行自动选择，mode=1代表开，mode=2代表关
        switchChangeCurtain(mode) {
            let cmdMotorStatus = null;
            switch (mode) {
                case 0:
                    cmdMotorStatus = this.MotorStatus == 'ON' ? 'OFF' : 'ON';
                    break;
                case 1:
                    cmdMotorStatus = 'ON';
                    break;
                case 2:
                    cmdMotorStatus = 'OFF';
                    break;
            }
            let requestParam = {
                "deviceId": this.curtainDeviceId,
                "serviceId": "Agriculture", //来源于协议指定
                "commandName": "Agriculture_Control_Motor", //来源于协议指定
                "paras": {
                    "MotorStatus": cmdMotorStatus
                }
            }
            console.log(JSON.stringify(requestParam));
            prompt.showToast("操作命令已发送");
            ajax.post('/platform/device/command/create', requestParam, (result) => {
                prompt.showToast("设备操作成功");
            });
        },

        //灯开关控制，mode=0，表示根据当前的灯状态进行自动选择，mode=1代表开，mode=2代表关
        switchChangeLight(mode) {
            let cmdLightStatus = null;
            switch (mode) {
                case 0:
                    cmdLightStatus = this.LightStatus == 'ON' ? 'OFF' : 'ON';
                    break;
                case 1:
                    cmdLightStatus = 'ON';
                    break;
                case 2:
                    cmdLightStatus = 'OFF';
                    break;
            }
            let requestParam = {
                "deviceId": this.lightDeviceId,
                "serviceId": "Agriculture", //来源于协议指定
                "commandName": "Agriculture_Control_Light", //来源于协议指定
                "paras": {
                    "LightStatus": cmdLightStatus
                }
            }
            console.log(JSON.stringify(requestParam));
            prompt.showToast("操作命令已发送");
            ajax.post('/platform/device/command/create', requestParam, (result) => {
                prompt.showToast("设备操作成功");
            });
        },

        switchSleepMode() {
            this.isSleep = !this.isSleep;
            if (this.isSleep) {
                //睡眠模式下关闭喜爱模式
                this.isLove = false;
                //开启随眠模式，执行关闭窗帘和关闭灯的操作
                this.switchChangeLight(2);
                this.switchChangeCurtain(2);
            } else {
                //解除随眠模式，执行打开窗帘的操作
                this.switchChangeCurtain(1);
            }
        },

        switchLoveMode() {
            this.isLove = !this.isLove;
            if (this.isLove) {
                //喜爱模式下关闭睡眠模式
                this.isSleep = false;
                //开启喜爱模式，执行关闭窗帘和开灯的操作
                this.switchChangeLight(1);
                this.switchChangeCurtain(2);
            } else {
                //解除喜爱模式不做任何的设备操作，纯粹切换状态变量
            }
        }
}
